/**
 * Copyright(C): CETC-32
 * @Description: 权限管理
 * @author: youqing
 * @version: 1.0
 * @date: 2020/9/11 10:55
 * 更改描述：
 */

package com.cetc32.dh.controller.rest;

import com.cetc32.dh.common.response.ResponseResult;
import com.cetc32.dh.common.utils.JWTUtil;
import com.cetc32.dh.config.RedisUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * 数据管理配置
 * @author: 徐文远
 * @version: 1.0
 * @date: 2020/9/11 10:55
 * @Description: MVC配置信息
 * 更改描述：
 */
@RestController
@RequestMapping("/rest/auth/")
public class AuthController {

    @Autowired
    RedisUtil redisUtil;

    /**
     * 用户登陆
     * @param username
     * @param password
     * @return ResponseResult
     * 备注:无
     */
    @PostMapping("/login")
    public ResponseResult login2(@RequestParam String username, @RequestParam String password){
        /*User user=userService.getUserByPass(username, password);
        Assert.notNull(user,"用户名或密码错误");*/
        long currentTimeMillis = System.currentTimeMillis();
        String token= JWTUtil.createToken("xuwenyuan",currentTimeMillis);
        redisUtil.set(username,currentTimeMillis,60*30);
        return ResponseResult.success(200,"登陆成功",token);
    }

    /**
     * 非授权用户登陆
     * @param message
     * @return ResponseResult
     * 备注:无
     */
    @PostMapping(path = "/unauthorized/{message}")
    public ResponseResult unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
        return ResponseResult.fail(message);
    }

    /**
     * 注销
     * @param request
     * @return ResponseResult
     * 备注:无
     */
    @DeleteMapping("/logout")
    @RequiresAuthentication
    public ResponseResult logout(HttpServletRequest request){
        String token=request.getHeader("Authorization");
        String username=JWTUtil.getUsername(token);
        redisUtil.del(username);
        return ResponseResult.success();
    }
}
